//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import memberInfo from '../comm/memberInfo.vue';
import recordItem from '../comm/recordItem.vue';
export default {
  name:'',
  //import引入的组件需要注入到对象中才能使用
  components: {memberInfo,recordItem},
  data() {
  return {
    minDate: '',
    maxDate: '',
    sixMonthsAgoDate:'',
    recordShow:false,
    recordData:[],
    timeTitle:'',
    iPnoneBottomBol:'',
    calendarInfo:{
      image:"https://thirdwx.qlogo.cn/mmopen/vi_32/PiajxSqBRaEL20ic6UvK5uGpGwoQvgBDOUicZcGgmGQgEConibbibBAznFP79icqK8zyp3muoMhvp0LoVhQ5z3Z9R98iboIx376YjU0fXnVRXThkch0icglUicxA6FQ/132",
      name:'一霎风雨',
      tag:'会员等级',
      details:[
        {
          clockName:'打卡天数',
          clockVal:'1'
        },
        {
          clockName:'打卡天数',
          clockVal:'1'
        }
      ],
    },
    id:'',
    query:{
      admin_type:1,
      id:'',
      page_type:1
    },
    partInfo:{},
    calendarInfo:{},
    //判断打卡，补卡的状态，今日打卡状态为1，今日未打卡状态状态为2，需要补卡状态为3
    dateStatus:0,
    recordDataTest:[],
    //补卡ID
    reissueId:'',
    pluginId:'',
    dayStatus:true,
    activityInfo:{},
    imgPath:'',
  };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    formatter(day) {
      let now = new Date();
      let toMonth = now.getMonth() + 1;
      let toDay = now.getDate();
      const month = day.date.getMonth() + 1;
      const date = day.date.getDate();
       //获取打卡开始日期
      if(this.recordData && this.recordData.length > 0) {
        this.recordData.map((item,index) => {
         let time =  new Date(item.created_at);
          let recordMonth = time.getMonth() + 1;
          //今日判断是没有打卡的，显示未打卡样式，走没打卡，发布打卡的逻辑,有打卡的话，点击查看打卡详情
          if(toMonth == month && toDay == date && ( time.getDate() != date 
            && !this.dayStatus)) {
              day.text = '今';
              day.className = 'current-class';
          }
          if((recordMonth ==  month && time.getDate() == date) && item.status == 2 && item.check_in_type == 2 ) {
            //补卡样式
            day.bottomInfo = '补卡';
            day.className = 'reissue-class';
            
          }
          if((recordMonth ==  month && time.getDate() == date) && item.status == 1 && item.check_in_type == 1 ) {
            day.className = 'today-class';
            day.text = date;
          }
         
        })
      }
      return day;
    },

    getiPnoneBottom() { //检测是否为苹果手机
      var userAgent = navigator.userAgent;
      var isiOS = !!userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
      isiOS?this.iPnoneBottomBol = true:this.iPnoneBottomBol = false;
    },
    //日期转化
    timestampToTime(timestamp) {
      var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      let Y = date.getFullYear() + "-";
      let M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
      let D = this.change(date.getDate()) + " ";
      let h = this.change(date.getHours()) + ":";
      let m = this.change(date.getMinutes());
      // let s = this.change(date.getSeconds());
      return Y + M + D;
    },
    timestampTime(timestamp) {
      var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      let Y = date.getFullYear() + "-";
      let M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
      let D = this.change(date.getDate()) + " ";
      let h = this.change(date.getHours()) + ":";
      let m = this.change(date.getMinutes());
      // let s = this.change(date.getSeconds());
      return Y + M + D + h + m;
    },
    change(t) {
      if (t < 10) {
        return "0" + t;
      } else {
        return t;
      }
    },
    calculateSixMonthsAgo() {
      const currentDate = new Date(); // 获取当前日期
      const sixMonthsAgoDate = new Date(currentDate); // 复制当前日期
      // 设置六个月前的日期
      sixMonthsAgoDate.setMonth(currentDate.getMonth() - 6);
      // 设置时间为 0 点 0 分 0 秒
      sixMonthsAgoDate.setHours(0, 0, 0, 0);
      // // 将六个月前的日期格式化为可读的字符串
      let minDate = sixMonthsAgoDate; // 格式化为字符串
      this.minDate = minDate;
    },
    calendarChange(event) {
      this.recordDataTest = [];
      //选择的日期
      let selectTime = new Date(event);
      let month = selectTime.getMonth() + 1

      //今天的日期
      let now = new Date();
      let toMonth = now.getMonth() + 1;
      let toDay = now.getDate();

      let timestampToTime = this.timestampToTime(new Date(event).getTime());
      //获取活动开始日期和结束日期的区间
      let endTime = new Date(this.partInfo?.activity?.end_time).getTime();
      let startTime = new Date(this.partInfo?.activity?.start_time).getTime();
      let currentTime = new Date().getTime()
      if((currentTime >= startTime && currentTime <= endTime)) { //判断在活动时间内
        this.timeTitle = timestampToTime;
        if(this.recordData.length > 0) {
          this.recordData.map((item,index) => {
            let time =  new Date(item.created_at);
            let recordMonth = time.getMonth() + 1;
            //判断记录列表有没有补卡的日期
            //今日没有打卡，去跳转打卡
            //判断打卡，补卡的状态，今日打卡状态为1，今日未打卡状态状态为2，需要补卡状态为3
            if(toMonth == month && toDay == selectTime.getDate() && (time.getDate() != selectTime.getDate()  
              && !this.dayStatus)) {
              //第二次连续打卡，不在活动详情打卡，在打卡日历打卡的情况
              this.recordShow = true;
              this.dateStatus = 2;
            }else if (
              toMonth == month && toDay == selectTime.getDate() && 
              (time.getDate() == selectTime.getDate()) 
              &&item.check_in_type == 1  && item.status == 1) {
              this.recordShow = true;
              this.dateStatus = 1;
              this.recordDataTest.push(this.recordData[index]);
            } else if((recordMonth ==  month && time.getDate() == selectTime.getDate()) && item.status == 1 && item.check_in_type == 1 ) {
              this.recordShow = true;
              this.dateStatus = 1;
              this.recordDataTest.push(this.recordData[index]);
            }
            else if((recordMonth ==  month && time.getDate() == selectTime.getDate()) && item.status == 2 && item.check_in_type == 2 ) {
              //补卡功能
              this.dateStatus = 3;
              this.recordShow = true;
              this.reissueId = this.recordData[index].activity?.supplement_goods_id;
              this.activityInfo = this.recordData[index];
              console.log(this.recordData[index]);
              this.recordDataTest.push(this.recordData[index]);
            } else {
              console.log(event);
              // this.$toast('打卡错误')
            }
          })
        }
          
        // this.recordShow = true;
      }
      // if(endTime.getTmie())
     
    },
    //补卡功能
    reissueOn() {
      this.$router.push(this.fun.getUrl("clockAdd", {},{ 
        id:this.query.id,pluginId:this.pluginId,goodsId:this.partInfo.goods_id,orderId: this.partInfo.order_id,actId:this.activityInfo.id,reissueId:this.reissueId }));
    },
    //打卡活动记录参加打卡接口
    partCheck() {
      this.$router.push(this.fun.getUrl("clockAdd", {},{ id: this.query.id,pluginId:this.pluginId,goodsId:this.partInfo.goods_id,orderId: this.partInfo.order_id }));
    },
    getInfo() {
      $http.get("plugin.check-in-rebate.frontend.participate-in.get-detail", {id:this.id}, "正在获取").then(
        response => {
          let res = response.data;
          if (response.result == 1) {
            
            res.is_error== true?this.calendarInfo.couponVal = '失败': this.calendarInfo.couponVal = res.continuous_day;
            this.partInfo = res;
            this.calendarInfo.priceVal = res.sum_day;
            
          } else {
             //分享有打卡的活动详情，不同的mid会导致会员显示的打卡信息错误，跳转到未参与的活动详情
             if(res.activity_id) {
              this.$router.replace(this.fun.getUrl("clockDetails", {},{activityId:res.activity_id,clockStatus:0}));
            } else {
              this.$dialog.alert({ message: response.msg });
            }
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    getMember() {
      $http.get("plugin.check-in-rebate.frontend.participate-in.get-Info", {}, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            let infoMember = {
              priceName:'打卡天数',
              priceVal:'0',
              couponName:'连续打卡天数',
              couponVal:'0'
            };
            this.calendarInfo = {...infoMember,...res.member};
            this.getInfo();
          } else {
            
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    recordListData() {
      //id查看自己的打卡记录,activity_id查看所有人记录
      // admin_type:1,是管理员状态（可以查看所有的打卡记录），但是只能自己看自己的打卡记录，所以写死状态
      $http.post("plugin.check-in-rebate.frontend.participate-in.check-in-log",this.query, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            let now = new Date();
            let toMonth = now.getMonth() + 1;
            let toDay = now.getDate();
            if(res.length > 0) {
              //查询是否有今天的打卡记录，没有就是未打卡状态
              let someTime = res.some((item,index) => {
                let time =  new Date(item.created_at);
                let recordMonth = time.getMonth() + 1;
                return recordMonth == toMonth && toDay == time.getDate();
              })
             
              this.dayStatus = someTime;
            }
            this.recordData = res;
            
          } else {
            this.$toast(response.msg);
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    // this.minDate = new Date(2024,4,21);
    this.calculateSixMonthsAgo();
    this.getiPnoneBottom();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {
    this.recordShow = false;
    this.query.page = 1;
    this.recordDataTest = [];
    this.recordData = [];
    let yz_basic_info = JSON.parse(localStorage.getItem("yz_basic_info"));
    this.imgPath = yz_basic_info.host;
    this.pluginId = yz_basic_info.plugin_setting?.check_in_rebate?.plugin_id;
    if(this.$route.query.id) {
      this.id = Number(this.$route.query.id);
      this.query.id = Number(this.$route.query.id);
       this.getMember();
       this.recordListData(); 
    }
    
  }, //如果页面有keep-alive缓存功能，这个函数会触发
  }